#include <assert.h>
#include <QImage>
#include <QDebug>
#include "vertex_object.h"
#include "table_drawer.h"
#include "geometry/table.h"

TableDrawer::~TableDrawer() {
    delete m_texture;
}

// 在resizeGL(),paintGL()之前调用, 仅调用一次。
void TableDrawer::init() {
    assert(m_vbo);
    assert(m_vao);
    // 顶点数据搬运至显存
    // m_vbo->allocate(tableVertics, sizeof(tableVertics));
    m_vbo->allocate(m_table->getVertexData()
            , m_table->getVertexPointSize() * 4 * sizeof(float));
    // 纹理图片512 x 512 -> 512 x 1024
    QImage img = QImage(":/res/air_hockey_surface.png");
    QSize newSize = QSize(512, 1024);
    QImage scaledImg = img.scaled(newSize, Qt::IgnoreAspectRatio);
    // 初始化纹理
    m_texture = new QOpenGLTexture(scaledImg);
    m_texture->setMinificationFilter(QOpenGLTexture::LinearMipMapLinear);
    m_texture->setMagnificationFilter(QOpenGLTexture::Linear);
    m_texture->release();
    // 设置属性
    TextureShaderProgram *txtProg = static_cast<TextureShaderProgram *>(m_program);
    m_program->setAttribute(m_program->getAttrPosition(), 2, 4 * sizeof(float), 0);
    m_program->setAttribute(txtProg->getAttrTextureCoordinate(), 2, 4 * sizeof(float), 2 * sizeof(GLfloat));
    // enable属性
    m_program->enableAttribute(m_program->getAttrPosition());
    m_program->enableAttribute(txtProg->getAttrTextureCoordinate());
}

void TableDrawer::draw(QMatrix4x4 &modelViewProjectM) {
    // 绘制图形
    m_vao->bind();
    m_program->bind();
    m_texture->bind();
    // 设置纹理
    QOpenGLShaderProgram *program =  m_program->getProgram();
    int textureLoc = static_cast<TextureShaderProgram *>(m_program)->getUniformTextureUnit();
    program->setUniformValue(textureLoc, 0);
    // 设置变换矩阵
    glUniformMatrix4fv(m_program->getUniformProjMatrix()
            , 1, false, modelViewProjectM.data());
    // 桌面
    glDrawArrays(GL_TRIANGLE_FAN, 0, 6);
}
